package com.example.littlepainter.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.util.TypedValue
import android.view.View
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

fun View.dp2px(dp:Int):Int{
    return (context.resources.displayMetrics.density*dp).toInt()
}

fun Context.dp2px(dp:Int):Int{
    return (resources.displayMetrics.density*dp).toInt()
}

fun Context.sp2px(sp:Int):Float{
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,sp.toFloat(),resources.displayMetrics)
}

/**
 * View -> Bitmap
 * */
suspend fun convertViewToBitmap(view: View):Bitmap = withContext(Dispatchers.IO){
    //创建一个空的画布Bitmap
    val bitmap = Bitmap.createBitmap(view.width,view.height, Bitmap.Config.ARGB_8888)
    //让canvas绘制的内容 绘制到我们指定的bitmap画布上
    val canvas = Canvas(bitmap)
    //将view绘制到canvas上   draw(canvas)
    view.draw(canvas)
    //返回bitmap画布
    bitmap
}

/**
 * 缩放Bitmap
 * */
suspend fun scaleBitmap(mBitmap: Bitmap, scale:Float):Bitmap = withContext(Dispatchers.IO){
     Bitmap.createScaledBitmap(
         mBitmap,
         (mBitmap.width*scale).toInt(),
         (mBitmap.height*scale).toInt(),
         true
     )
}